package com.campus.customer.bean;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;

public class WechatServerValidation {

    private static final String TOKEN = "your_wechat_token"; // 微信公众号设置的Token

    public static boolean validateSignature(String weChatToken, String signature, String timestamp, String nonce) {
        // 将token、timestamp、nonce三个参数进行字典序排序
        String[] arr = new String[]{weChatToken, timestamp, nonce};
        Arrays.sort(arr);
        // 将三个参数字符串拼接成一个字符串进行sha1加密
        StringBuilder sb = new StringBuilder();
        for (String s : arr) {
            sb.append(s);
        }
        String encryptedStr = sha1(sb.toString());
        // 将加密后的字符串与signature进行对比，标识该请求是否来自微信服务器
        return encryptedStr.equals(signature);
    }

    private static String sha1(String input) {
        try {
            MessageDigest digest = MessageDigest.getInstance("SHA-1");
            byte[] result = digest.digest(input.getBytes());
            StringBuilder sb = new StringBuilder();
            for (byte b : result) {
                String hex = Integer.toHexString(b & 0xff);
                if (hex.length() == 1) {
                    sb.append("0");
                }
                sb.append(hex);
            }
            return sb.toString();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            return null;
        }
    }

    public static void main(String[] args) {
        String weChatToken = "your_wechat_token"; // 微信公众号设置的Token
        // 在这里替换为实际从微信服务器收到的参数值
        String signature = "signature_from_wechat";
        String timestamp = "timestamp_from_wechat";
        String nonce = "nonce_from_wechat";

        // 验证签名是否合法
        if (validateSignature(weChatToken, signature, timestamp, nonce)) {
            System.out.println("验证成功，该请求来自微信服务器！");
        } else {
            System.out.println("验证失败，该请求不是来自微信服务器！");
        }
    }
}
